<template>
  <div class="attendance-absen">
    <div class="absen-title">
      <div class="select-box">
        <div class="select_li mini">
          <el-select v-model="yearData" placeholder="请选择" size="small" @change="selectFun('year')" value-key="year">
            <el-option v-for="item in yearOptions" :key="item.year" :label="item.year + '年'" :value="item"></el-option>
          </el-select>
        </div>
        <div class="select_li mini">
          <el-select v-model="monthData" placeholder="请选择" size="small" @change="selectFun">
            <el-option
              v-for="item in monthOptions"
              :key="item.month"
              :label="item.month ? item.month + '月' : '全部'"
              :value="item.month"></el-option>
          </el-select>
        </div>
      </div>
      <div class="select-box">
        <el-cascader
          placeholder="请选择部门/人员进行查询"
          :options="orgOptions"
          :props="propsCascader"
          v-model="orgPerson"
          @change="handleChange"
          size="small"
          :show-all-levels="true"
          ref="cascader"
          clearable
          filterable></el-cascader>
        <el-button type="primary" size="small" v-if="isAdd" @click="add">新 建</el-button>
        <el-button type="primary" size="small" @click="exportData">导 出</el-button>
      </div>
    </div>
    <div class="attendance-absen-main">
      <absen-table ref="right2" :buttonList="buttonList" @edit="edit"></absen-table>
    </div>
    <XnDialog
      title="旷工人员"
      :visible.sync="addDialogShow"
      width="60%"
      class="branch_dialog"
      @close="addDialogShow = false">
      <div class="dia_con" v-if="addDialogShow">
        <el-form label-position="right" label-width="120px">
          <el-form-item label="部门：">
            <el-input size="small" disabled v-model="formData.orgName"></el-input>
          </el-form-item>
          <el-form-item label="人员：">
            <el-select v-model="formData.userId" placeholder="请选择" size="small">
              <el-option
                v-for="item in userOptions"
                :key="item.userId"
                :label="item.userName"
                :value="item.userId"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="旷工开始时间：">
            <el-date-picker
              v-model="formData.startTime"
              type="datetime"
              placeholder="选择日期时间"
              value-format="yyyy-MM-dd HH:mm:ss"
              format="yyyy-MM-dd HH:mm"
              size="small"
              :picker-options="pickerOptions"></el-date-picker>
          </el-form-item>
          <el-form-item label="旷工结束时间：">
            <el-date-picker
              v-model="formData.endTime"
              type="datetime"
              placeholder="选择日期时间"
              value-format="yyyy-MM-dd HH:mm:ss"
              format="yyyy-MM-dd HH:mm"
              size="small"
              :picker-options="pickerOptions"></el-date-picker>
          </el-form-item>
          <el-row>
            <el-col :span="12">
              <el-form-item label="创建日期：">{{ formData.creatTime }}</el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="创建人：">{{ formData.creatName }}</el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div class="sunmit_tips" slot="footer">
        <el-button type="primary" @click="close('0')" size="small" plain class="btnBorder">取消</el-button>
        <el-button type="primary" @click="close('1')" size="small" class="btnBg">保存</el-button>
      </div>
    </XnDialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import moment from 'moment'
import AbsenTable from './components/AbsenTable'
import XnDialog from '@com/xnDialog.vue'
import {
  getDataPermissions,
  getSearchTimeList,
  addNeglectRecord,
  checkIsOverlap,
  exportNeglectRecord,
} from '@apis/api-attendance.js'
moment.locale('zh-cn')
export default {
  components: {
    AbsenTable,
    XnDialog,
  },
  props: {
    orgId: String,
  },
  computed: {
    ...mapGetters('role', ['isOtherRole', 'isNormalRole', 'isAdminRole', 'isMainRole', 'isOrgRole', 'isPartRole']),
    pickerOptions() {
      const startYear = '2023-01-01'
      const lastYear = moment().format('YYYY-MM-DD')
      return {
        disabledDate(time) {
          return (
            moment(time).format('YYYYMMDDHHmmss') < moment(startYear).format('YYYYMMDD000000') ||
            moment(time).format('YYYYMMDDHHmmss') > moment(lastYear).format('YYYYMMDD235959')
          )
        },
      }
    },
  },
  data() {
    return {
      orgOptions: [],
      orgPerson: '',
      propsCascader: {
        // lazy: true,
        // expandTrigger: 'hover',
        checkStrictly: true,
        label: 'text',
        value: 'id',
        multiple: false,
      },
      moment: moment,
      param2: {
        userId: '',
        orgId: '',
      },
      yearOptions: [],
      yearData: {},
      monthOptions: [],
      monthData: '',
      buttonList: [],
      addDialogShow: false,
      formData: {
        id: '',
        orgName: JSON.parse(localStorage.PSKH_USERINFO).loginPostInfo.orgName,
        orgId: JSON.parse(localStorage.PSKH_USERINFO).loginPostInfo.orgId,
        userName: '',
        userId: '',
        startTime: '',
        endTime: '',
        creatTime: moment().format('YYYY-MM-DD'),
        creatName: JSON.parse(localStorage.PSKH_USERINFO).userName,
      },
      userOptions: [],
      isAdd: false,
    }
  },
  created() {
    if (this.isAdminRole) {
      this.isAdd = true
      this.param2.orgId = JSON.parse(localStorage.PSKH_USERINFO).loginPostInfo.orgId
      this.getDataPermissions()
      this.getSearchTimeList()
    }
  },
  mounted() {},
  methods: {
    initData() {
      this.$refs.right2.getData(this.yearData.year, this.monthData, this.param2.orgId, this.param2.userId)
    },

    handleChange(node) {
      // let checkNodes = this.$refs.cascader.getCheckedNodes()
      if (node && node.length === 1) {
        this.param2.orgId = node[0]
        this.param2.userId = ''
      } else if (node && node.length === 2) {
        this.param2.orgId = node[0]
        this.param2.userId = node[1]
      } else if (node && node.length === 3) {
        this.param2.orgId = node[1]
        this.param2.userId = node[2]
      } else {
        this.param2.userId = ''
        this.param2.orgId = ''
      }
      this.initData()
    },
    getSearchTimeList() {
      getSearchTimeList().then(res => {
        if (res.status === 200) {
          this.yearOptions = res.data
          const arr = res.data.filter(item => {
            return item.isChoose
          })
          this.yearData = arr[0]
          this.monthOptions = [{ month: '' }, ...res.data[0].monthList]
          this.initData()
        }
      })
    },
    getDataPermissions() {
      getDataPermissions({
        type: '2',
      }).then(res => {
        if (res.status === 200) {
          const arr = []
          res.data.forEach(item => {
            const arr1 = []
            item.userList.forEach(li => {
              arr1.push({
                text: li.userName,
                id: li.userId,
              })
            })
            arr.push({
              text: item.orgName,
              id: item.orgId,
              children: arr1,
            })
          })
          this.orgOptions = arr
          if (this.isAdd) {
            this.userOptions = res.data[0].userList
          }
        }
      })
    },
    selectFun(type) {
      if (type === 'year') {
        this.monthOptions = [{ month: '' }, ...this.yearData.monthList]

        this.monthData = this.yearData.monthList[0].month
      }
      this.initData()
    },
    exportData() {
      const type = this.isAdd ? '1' : '2'
      const req = `?year=${this.yearData.year}&month=${this.monthData}&orgId=${this.param2.orgId}&userId=${this.param2.userId}&type=${type}`
      const link = document.createElement('a')
      link.href = exportNeglectRecord(req)
      link.target = 'targetName'
      link.click()
    },
    add() {
      this.formData = {
        id: '',
        orgName: JSON.parse(localStorage.PSKH_USERINFO).loginPostInfo.orgName,
        orgId: JSON.parse(localStorage.PSKH_USERINFO).loginPostInfo.orgId,
        userName: '',
        userId: '',
        startTime: '',
        endTime: '',
        creatTime: moment().format('YYYY-MM-DD'),
        creatName: JSON.parse(localStorage.PSKH_USERINFO).userName,
      }
      this.addDialogShow = true
    },
    close(type) {
      if (type === '1') {
        if (!this.formData.userId) {
          return this.$message.warning('请选择人员')
        }
        if (!this.formData.startTime) {
          return this.$message.warning('请选择旷工开始时间')
        }
        if (!this.formData.endTime) {
          return this.$message.warning('请选择旷工结束时间')
        }
        if (moment(this.formData.endTime).diff(moment(this.formData.startTime), 'minutes') <= 0) {
          return this.$message.warning('旷工开始时间不能小于旷工结束时间')
        }
        const arr = this.userOptions.filter(item => {
          return item.userId === this.formData.userId
        })
        this.formData.userName = arr[0].userName
        checkIsOverlap(this.formData).then(res => {
          if (res.status === 200) {
            if (res.message === '1') {
              addNeglectRecord(this.formData).then(res => {
                if (res.status === 200) {
                  this.$message.success('添加成功')
                  this.addDialogShow = false
                  this.initData()
                }
              })
            } else {
              this.$alert(res.message, '提示', {
                confirmButtonText: '确定',
                callback: action => {},
              })
            }
          }
        })
      }
      if (type === '0') {
        this.addDialogShow = false
      }
    },
    edit(data) {
      this.formData.id = data.id
      this.formData.startTime = data.startTime
      this.formData.endTime = data.endTime
      this.formData.userName = data.userName
      this.formData.userId = data.userId
      this.formData.orgName = data.orgName
      this.formData.orgId = data.orgId
      this.addDialogShow = true
    },
  },
}
</script>

<style lang="scss" scoped>
.attendance-absen {
  height: 100%;
  font-size: 14px;
  width: 100%;

  .absen-title {
    height: 56px;
    // box-shadow: inset 0px -2px 9px 0px rgba(0, 0, 0, 0.15);
    background-color: #fff;
    display: flex;
    align-items: center;
    justify-content: space-between;
    // padding: 0 20px;
    font-size: 16px;
    .select-box {
      display: flex;
      align-items: center;
      .select_li {
        display: flex;
        align-items: center;
        margin-right: 20px;
        &.mini {
          .el-select {
            width: 100px;
          }
        }
      }
      .el-button {
        margin-left: 20px;
      }
    }
  }

  .absen-work-tips {
    color: #999999;
  }

  .attendance-absen-main {
    height: calc(100% - 56px);
    background-color: #fff;
  }
}
.dia_con {
  .el-form-item {
    margin-bottom: 10px;
  }
  .el-input {
    width: 50%;
  }
  .el-select {
    width: 50%;
  }
}
.sunmit_tips {
  text-align: center;
}
</style>
